﻿using AutoMapper;
using B.Z.BasicData.API.Read.DTO.ExcuseDtos;
using B.Z.BasicData.Domain.Entity.Excused;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.BasicData.API.Read.Application.Excused
{
    public class ExcuseDetailQueryCommandHandler : IRequestHandler<ExcuseDetailQueryCommand, APIResult<List<ExcusedDto>>>
    {
        private readonly IBaseRepository<T_Excused> excusedRepository;
        private readonly IBaseRepository<T_Department> departRepository;
        private readonly IBaseRepository<T_ExcusedType> typeRepository;

        public ExcuseDetailQueryCommandHandler(IBaseRepository<T_Excused> excusedRepository, IBaseRepository<T_ExcusedType> typeRepository, IBaseRepository<T_Department> departRepository)
        {
            this.excusedRepository = excusedRepository;
            this.typeRepository = typeRepository;
            this.departRepository = departRepository;
        }
        public Task<APIResult<List<ExcusedDto>>> Handle(ExcuseDetailQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ExcusedDto>> result = new APIResult<List<ExcusedDto>>();
            result.Code = APIEnum.ok;
            result.Message = "获取成功";
            var dtolist = from a in excusedRepository.GetAll().AsNoTracking()
                          join b in departRepository.GetAll().AsNoTracking()
                          on a.DepartId equals b.Id
                          join c in typeRepository.GetAll().AsNoTracking()
                          on a.ExcusedType equals c.Id
                          select new ExcusedDto
                          {
                              Id = a.Id,
                              Name = a.Name,
                              DepartId = a.DepartId,
                              ExcusedType = a.ExcusedType,
                              StartDateTime = a.StartDateTime,
                              EndDateTime = a.EndDateTime,
                              TotalHour = a.TotalHour,
                              BackDateTime = a.BackDateTime,
                              Reason = a.Reason,
                              LeaderName = a.LeaderName,
                              Status = a.Status,
                              Remark = a.Remark,
                              WhyRefuse = a.WhyRefuse,
                              TypeName = c.TypeName,
                              DepartName = b.DepartName,
                              CreateTime = a.CreateTime,
                              Uid = a.Uid,
                          };
            result.Data = dtolist.Where(x => x.Name == request.UserName && x.StartDateTime.Month == request.MonthNum).ToList();
            return Task.FromResult(result);
        }
    }
}
